package com.zhiyou100.util.message;

import lombok.SneakyThrows;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

/**
 * 发送邮件
 *
 * @author yang
 * @version 1.0.0
 * @date 2020-09-24 16:25
 */
public class SendMail {
    /**
     * 邮箱名字
     */
    public static final String MY_EMAIL_ACCOUNT = "javayanglei2001@126.com";
    /**
     * 授权码
     */
    public static final String MY_EMAIL_PASSWORD = "OAJFKDISCBDVRGJE";
    /**
     * SMTP服务器: smtp.126.com
     */
    public static final String EMAIL_163_SMTP_HOST = "smtp.126.com";
    /**
     * 端口号
     * QQ邮箱：SMTP服务器是 smtp.qq.com，端口是465/587；
     * 163邮箱：SMTP服务器是 smtp.163.com，端口是 25;
     * Gmail邮箱：SMTP服务器是 smtp.gmail.com，端口是465/587。
     */
    public static final String EMAIL_163_SMTP_PORT = "25";


    /**
     * 给指定的人发送邮件
     *
     * @param receiver 接受人
     * @param subject  标题
     * @param content  正文
     */
    @SneakyThrows
    public static void sendMessage(String receiver, String subject, String content) {
        //属性集
        Properties p = new Properties();
        p.setProperty("mail.smtp.host", EMAIL_163_SMTP_HOST);
        p.setProperty("mail.smtp.port", EMAIL_163_SMTP_PORT);
        p.setProperty("mail.smtp.socketFactory.port", EMAIL_163_SMTP_PORT);
        //是否需要认证
        p.setProperty("mail.smtp.auth", "true");
        p.setProperty("mail.smtp.socketFactory.class", "SSL_FACTORY");
        //获取连接
        Session session = Session.getInstance(p, new Authenticator() {
            // 设置认证账户信息
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(MY_EMAIL_ACCOUNT, MY_EMAIL_PASSWORD);
            }
        });
        //设置debug测试
        session.setDebug(true);
        System.out.println("创建邮件");
        MimeMessage message = new MimeMessage(session);
        // 发件人
        message.setFrom(new InternetAddress(MY_EMAIL_ACCOUNT));
        // 收件人和抄送人
        message.setRecipients(Message.RecipientType.TO, receiver);
        // 内容(这个内容还不能乱写,有可能会被SMTP拒绝掉;多试几次吧)
        message.setSubject(subject);
        message.setContent(content, "text/html;charset=UTF-8");
        message.setSentDate(new Date());
        message.saveChanges();//保存设置
        System.out.println("准备发送");
        Transport.send(message);
        System.out.println("发送成功！");
    }
}
